<template>
  <div class="emotional-companion-page">
    <van-nav-bar
      title="情感陪伴"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
      class="custom-nav-bar"
    />

    <div class="feature-intro">
      <div class="intro-content">
        <div class="intro-icon">💝</div>
        <div class="intro-text">
          <h3>AI情感陪伴{{ currentMode ? ` - ${currentMode}` : '' }}</h3>
          <p>情感识别与温暖回应，给予心理支持</p>
        </div>
      </div>

      <!-- 陪伴类型标签 -->
      <div class="companion-tabs">
        <div class="mode-title">选择陪伴类型：</div>
        <div class="tabs-container">
          <div
            v-for="mode in companionModes"
            :key="mode.name"
            :class="['mode-tab', { active: currentMode === mode.name }]"
            @click="selectMode(mode)"
          >
            <span class="tab-icon">{{ mode.icon }}</span>
            <span class="tab-name">{{ mode.name }}</span>
          </div>
        </div>
      </div>

      <!-- 示例话题 -->
      <div class="intro-examples" v-if="currentMode">
        <div class="example-title">💡 试试这些{{ currentMode }}话题：</div>
        <div class="example-tags">
          <span
            v-for="example in currentExamples"
            :key="example"
            class="example-tag"
            @click="setExample(example)"
          >
            {{ example }}
          </span>
        </div>
      </div>
    </div>

    <div class="chat-container" ref="chatContainer">
      <div
        v-for="(message, index) in messages"
        :key="index"
        :class="['message-item', message.type]"
      >
        <div class="message-avatar">
          {{ message.type === 'user' ? '👤' : '💝' }}
        </div>
        <div class="message-content">
          <div class="message-text">{{ message.content }}</div>
          <div class="message-time">{{ formatTime(message.timestamp) }}</div>
        </div>
      </div>
    </div>

    <div class="input-container">
      <van-field
        v-model="inputText"
        placeholder="分享你的心情..."
        type="textarea"
        rows="2"
        autosize
      />
      <van-button
        type="primary"
        :loading="isLoading"
        @click="sendMessage"
        :disabled="!inputText.trim()"
      >
        发送
      </van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { showToast } from 'vant'
import { useRoute } from 'vue-router'
import aiService from '@/services/aiService'

const route = useRoute()

const inputText = ref('')
const messages = ref<Array<{
  type: 'user' | 'ai'
  content: string
  timestamp: number
}>>([])
const isLoading = ref(false)
const currentMode = ref<string>('')

// 陪伴模式配置
const companionModes = ref([
  {
    name: '心理疏导',
    icon: '🧘',
    description: '专业心理疏导服务',
    examples: ['我最近压力很大', '感觉很焦虑怎么办', '工作让我很烦躁', '如何调节情绪']
  },
  {
    name: '情感倾诉',
    icon: '💬',
    description: '温暖的情感倾听',
    examples: ['今天发生了不开心的事', '我想找人聊聊', '心情不太好', '需要有人理解我']
  },
  {
    name: '压力缓解',
    icon: '🌸',
    description: '有效的压力释放方法',
    examples: ['工作压力太大了', '学习压力很重', '如何放松心情', '缓解压力的方法']
  },
  {
    name: '正能量激励',
    icon: '⭐',
    description: '积极正面的激励话语',
    examples: ['我需要鼓励', '感觉没有动力', '想要正能量', '给我一些激励']
  },
  {
    name: '冥想引导',
    icon: '🕯️',
    description: '专业冥想指导服务',
    examples: ['教我冥想', '如何静心', '冥想的好处', '放松身心的方法']
  }
])

// 当前示例
const currentExamples = computed(() => {
  if (!currentMode.value) return []
  const mode = companionModes.value.find(m => m.name === currentMode.value)
  return mode ? mode.examples : []
})

// 选择模式
const selectMode = (mode: any) => {
  currentMode.value = mode.name
  showToast(`已切换到${mode.name}模式`)
}

// 设置示例
const setExample = (example: string) => {
  inputText.value = example
}

const sendMessage = async () => {
  if (!inputText.value.trim()) return

  messages.value.push({
    type: 'user',
    content: inputText.value,
    timestamp: Date.now()
  })

  const userMessage = inputText.value
  inputText.value = ''
  isLoading.value = true

  // 添加AI消息占位符
  const aiMessageIndex = messages.value.length
  messages.value.push({
    type: 'ai',
    content: '',
    timestamp: Date.now()
  })

  let accumulatedText = ''

  try {
    console.log('🚀 开始流式情感陪伴:', userMessage)

    // 使用流式输出
    await aiService.emotionalCompanionStream(
      12345,
      userMessage,
      // onMessage回调
      (content: string) => {
        console.log('📝 收到陪伴内容:', content)
        accumulatedText += content
        messages.value[aiMessageIndex].content = accumulatedText
      },
      // onComplete回调
      () => {
        console.log('✅ 流式陪伴完成')
        isLoading.value = false
      },
      // onError回调
      async (error: any) => {
        console.error('❌ 流式陪伴失败，尝试非流式陪伴:', error)

        // 流式输出失败，尝试非流式输出
        try {
          const response = await aiService.emotionalCompanion(12345, userMessage)
          if (response.code === 200) {
            messages.value[aiMessageIndex].content = response.data || '我在这里陪伴你。'
          } else {
            messages.value[aiMessageIndex].content = '我现在有点累了，稍后再聊好吗？'
          }
        } catch (fallbackError) {
          console.error('非流式输出也失败:', fallbackError)
          messages.value[aiMessageIndex].content = '我现在有点累了，稍后再聊好吗？'
        }

        isLoading.value = false
      }
    )

  } catch (error) {
    console.error('情感陪伴失败:', error)

    // 备选方案：直接调用非流式API
    try {
      const response = await aiService.emotionalCompanion(12345, userMessage)
      if (response.code === 200) {
        messages.value[aiMessageIndex].content = response.data || '我在这里陪伴你。'
      } else {
        messages.value[aiMessageIndex].content = '我现在有点累了，稍后再聊好吗？'
      }
    } catch (fallbackError) {
      console.error('备选方案失败:', fallbackError)
      messages.value[aiMessageIndex].content = '我现在有点累了，稍后再聊好吗？'
    }

    isLoading.value = false
  }
}

const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  messages.value.push({
    type: 'ai',
    content: '你好！我是你的情感陪伴助手。无论你开心还是难过，都可以和我分享。我会倾听并给你温暖的回应。',
    timestamp: Date.now()
  })
})
</script>

<style scoped>
.emotional-companion-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.custom-nav-bar {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.feature-intro {
  margin: 16px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 20px;
  backdrop-filter: blur(10px);
}

.intro-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.intro-icon {
  font-size: 40px;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(250, 112, 154, 0.1);
  border-radius: 16px;
}

.intro-text h3 {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
}

.intro-text p {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0;
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message-item {
  display: flex;
  gap: 12px;
  max-width: 85%;
}

.message-item.user {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.message-item.ai {
  align-self: flex-start;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  background: rgba(255, 255, 255, 0.9);
  flex-shrink: 0;
}

.message-content {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 12px 16px;
  backdrop-filter: blur(10px);
}

.message-item.user .message-content {
  background: rgba(250, 112, 154, 0.9);
  color: white;
}

.message-text {
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 8px;
}

.message-time {
  font-size: 12px;
  color: #95a5a6;
  text-align: right;
}

.message-item.user .message-time {
  color: rgba(255, 255, 255, 0.8);
}

.input-container {
  padding: 16px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  display: flex;
  gap: 12px;
  align-items: flex-end;
}
</style>
